﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.PurchaseCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.PurchaseCommandHandler
{
    /// <summary>
    /// 采购/委外命令处理
    /// </summary>
    public class PurchasedetailsCreateCommandHandler : IRequestHandler<PurchasedetailsCreateCommand, APIResult<object>>
    {

        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 采购/委外订单
        /// </summary>
        private readonly IBaseRepository<Purchasedetails> purchasedetailsRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="purchasedetailsRepository"></param>
        public PurchasedetailsCreateCommandHandler(IMapper mapper, IBaseRepository<Purchasedetails> purchasedetailsRepository)
        {
            this.mapper = mapper;
            this.purchasedetailsRepository = purchasedetailsRepository;
        }

        public async Task<APIResult<object>> Handle(PurchasedetailsCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            var info = mapper.Map<Purchasedetails>(request);
            var data = purchasedetailsRepository.AddAsync(info).Result;
            if (data > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = data;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
            }
            return await Task.FromResult(result);
        }
    }
}
